<script setup lang="ts">
import type { ISubmission } from '@fl/api/bidding-api/model'
import type { FormInstance } from 'element-plus'
import type { VxePagerEvents } from 'vxe-table'

import breadCrumb from '@/components/bread-crumb.vue'
import Footer from '@/pages/footer/footer.vue'
import { useGetissuesList, useIssueSave } from '@fl/api/bidding-api'
import { SearchTable } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import { useMessage } from '@fl/hooks/web/use-message'
import { ElFormItem } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { reactive, ref } from 'vue'

const { push } = useRouter()

// 公告状态

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))
const page = computed(() => {
    return {
        pageNum: tablePage.value.currentPage,
        pageSize: tablePage.value.pageSize,
    }
})
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}
const { data, refetch } = useGetissuesList(page)

const gridOptions = reactive({
    columns: [
        { field: 'submissionTime', title: '提出时间' },
        { field: 'description', title: '问题描述' },
        { field: 'replyContent', title: '回复' },
        { field: 'status', slots: { default: 'status' }, title: '操作' },
    ],
    height: 600,
    showHeader: true,
    showOverflow: true,
    showToolbar: false,
})
watchEffect(() => {
    if (data.value) {
        tablePage.value.total = Number(data.value.total ?? 0)
    }
})
function toDetail(row) {
    push({
        path: '/issure/detail',
        query: {
            id: row.id,
        },
    })
}
const dialogVisible = ref(false)
const form = ref<ISubmission>({
    description: '',
    descriptionFiles: [],
    id: undefined,
    phoneNumber: '',
    replyContent: '',
    replyFileIds: [],
    submitter: '',
})
const rules = reactive<any>({
    description: [
        {
            message: '请输入问题描述',
            required: true,
        },
    ],
    phoneNumber: [
        {
            message: '请输入手机号',
            required: true,
        },
        { message: '手机号码格式不正确', pattern: /^1[3-9]\d{9}$/, trigger: 'blur' },
    ],
    submitter: [
        {
            message: '请输入姓名',
            required: true,
        },
        {
            max: 20,
            message: '请输入2-20个字符',
            min: 2,
        },
    ],
})

const ruleFormRef = ref<FormInstance>()
const tenderFile = ref<any[]>([])

function uploadSuc(fileInfo) {
    const data = cloneDeep(fileInfo)
    const names = data.name.split('.')
    const obj = {}
    obj.size = data.file.size
    obj.fileName = data.file.name
    obj.fileSuffix = names[names.length - 1]
    obj.fileUrl = data.url
    form.value.descriptionFiles.push(obj)
}
function removeCall(data) {
    console.log(data)
    const index = form.value.descriptionFiles.findIndex(item => item.fileUrl === data.validUrl)
    if (index > -1) {
        form.value.descriptionFiles.splice(index, 1)
    }
}

const { isPending, mutateAsync } = useIssueSave()
const { createMessage } = useMessage()
async function submitForm(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    const isValid = await formEl.validate()
    if (isValid) {
        const result = await mutateAsync(unref(form))
        console.log(result)
        if (result.code === 200) {
            createMessage.success('提交成功')
            dialogVisible.value = false
            await refetch()
        }
        else {
            createMessage.error('提交失败')
        }
    }
}
const customerList = [{ name: 'root-index', title: '首页' }, { name: 'root-issure', title: '用户反馈' }]
</script>

<template>
    <div class="container p-20px">
        <breadCrumb :customer-list="customerList"
                    class="m-20"
        />

        <ElCard shadow="never">
            <div class="font-size-28px color-red font-bold">
                期待您的反馈
            </div>

            <el-button type="primary"
                       class="mt-10px"
                       @click="dialogVisible = true"
            >
                我要反馈
            </el-button>
        </ElCard>

        <el-dialog v-model="dialogVisible"
                   title="用户反馈"
                   width="50%"
        >
            <el-form ref="ruleFormRef"
                     :model="form"
                     :rules="rules"
                     label-width="80px"
            >
                <ElFormItem label="问题描述"
                            required
                            prop="description"
                >
                    <el-input v-model="form.description"
                              type="textarea"
                    />
                </ElFormItem>

                <ElFormItem label="上传图片"
                            prop="descriptionFiles"
                >
                    <FlUpload v-model="tenderFile"
                              :limit="10"
                              list-type="picture-card"
                              accept=".png,.jpg,.jpeg"
                              tips
                              @success="uploadSuc"
                              @remove="removeCall"
                    />
                </ElFormItem>

                <ElFormItem label="姓名"
                            required
                            prop="submitter"
                >
                    <el-input v-model="form.submitter" />
                </ElFormItem>

                <ElFormItem label="手机号"
                            required
                            prop="phoneNumber"
                >
                    <el-input v-model="form.phoneNumber" />
                </ElFormItem>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>

                    <el-button :loading="isPending"
                               @click="submitForm(ruleFormRef)"
                    >提交</el-button>

                </span>
            </template>
        </el-dialog>

        <ElCard shadow="never"
                class="mt-20px"
        >
            <SearchTable v-bind="gridOptions"
                         v-model:pager="tablePage"
                         :data="data?.rows"
                         @page-change="handlePageChange"
            >
                <template #status="{ row }">
                    <el-link type="primary"
                             @click="toDetail(row)"
                    >
                        查看详情
                    </el-link>
                </template>
            </SearchTable>
        </ElCard>
    </div>

    <Footer />
</template>

<style scoped lang="scss">
.container {
    padding: 0 10%;
    margin: auto;
    padding-bottom: 60px;
    :deep(.el-header) {
        padding-left: 0;
    }
    //:deep(.vxe-table--render-default.border--full .vxe-table--header-wrapper) {
    //    background: transparent;
    //}
    :deep(.vxe-toolbar) {
        padding: 0;
    }
}
</style>
